import { Message } from "element-ui";

let websock = null;
let messageCallback = null;
let errorCallback = null;
let wsUrl = "";
let tryTime = 0;
let userId = null;
let HeartbeatTimeout = null;
let HeartbeatTimeoutover = null;
let HeartbeatTimeoutnum=1
let errCallbacknum = 0;
let errCallbacktime = 0;
let errCallbacktover = null
// 接收ws后端返回的数据
function websocketonmessage(e) {
  let jsondata = JSON.parse(e.data);
  //console.log(jsondata);
  userId = jsondata.userId;
  if (jsondata.cmd == 7) {
    //console.log("getpong");
    //清除时间
    errCallbacknum = 0;
    HeartbeatTimeoutnum=1
    clearTimeout(HeartbeatTimeout);
    HeartbeatTimeout = null;
    clearTimeout(HeartbeatTimeoutover);
    HeartbeatTimeoutover = null;
    clearTimeout(errCallbacktover);
    errCallbacktover = null;
    //重启心跳
    heartbeat();
  } else if (jsondata.cmd == 4) {
    websock.send(
      JSON.stringify({
        cmd: 4,
        msg: "pong",
        msgType: "",
        userId: jsondata.userId,
      })
    );
  } else {
    window.dispatchEvent(
      new CustomEvent("onmessageWS", {
        detail: {
          data: JSON.parse(e.data),
        },
      })
    );
  }
  //单页面
  //messageCallback(JSON.parse(e.data))
}

/**
 * 发起websocket连接
 * @param {Object} agentData 需要向后台传递的参数数据
 */
function websocketSend(agentData) {
  // 加延迟是为了尽量让ws连接状态变为OPEN
  setTimeout(() => {
    // 添加状态判断，当为OPEN时，发送消息
    if (websock.readyState === websock.OPEN) {
      // websock.OPEN = 1
      // 发给后端的数据需要字符串化
      if (agentData == "") {
        websock.send(JSON.stringify(agentData));
      }
    }
    if (websock.readyState === websock.CLOSED) {
      // websock.CLOSED = 3
      //console.log("websock.readyState=3");
      //Message.error("ws连接异常，请稍候重试");
      //errorCallback()
    }
  }, 500);
}

// 关闭ws连接
function websocketclose(e) {
  // e.code === 1000  表示正常关闭。 无论为何目的而创建, 该链接都已成功完成任务。
  // e.code !== 1000  表示非正常关闭。
  if (e && e.code !== 1000) {
    //console.log(e,new Date().getTime())
    //initWebSocket()
    // Message.error('ws连接异常，请稍候重试')
    // errorCallback()
    // 如果需要设置异常重连则可替换为下面的代码，自行进行测试
    // if (tryTime < 1) {
    //   setTimeout(function() {
    //    websock = null
    //    tryTime++
    //    initWebSocket()
    //    console.log(`第${tryTime}次重连`)
    //  }, 3 * 1000)
    // } else {
    //  Message.error('重连失败！请稍后重试')
    // }
  }
}
// 建立ws连接
function websocketOpen(e) {
  //console.log('ws连接成功',e)
  // 加延迟是为了尽量让ws连接状态变为OPEN
  errCallbacknum = 0;
  HeartbeatTimeoutnum=1
  clearTimeout(HeartbeatTimeout);
  HeartbeatTimeout = null;
  clearTimeout(HeartbeatTimeoutover);
  HeartbeatTimeoutover = null;
  clearTimeout(errCallbacktover);
  errCallbacktover = null;
  setTimeout(() => {
    heartbeat();
  }, 1000);
}

// 初始化weosocket
function initWebSocket() {
  if (typeof WebSocket === "undefined") {
    Message.error("您的浏览器不支持WebSocket，无法获取数据");
    return false;
  }

  // ws请求完整地址
  const requstWsUrl = wsUrl;
  websock = new WebSocket(requstWsUrl);

  websock.onmessage = function(e) {
    websocketonmessage(e);
  };
  websock.onopen = function() {
    websocketOpen();
  };
  websock.onerror = function() {
    //Message.error("ws连接异常，请稍候重试");
    //errorCallback()
  };
  websock.onclose = function(e) {
    //console.log('关闭')
    websocketclose(e);
  };
}
// 心跳机制
function heartbeat() {
  //console.log(websock.readyState);
  HeartbeatTimeout = setInterval(function() {
    if (websock.readyState === websock.OPEN) {
      // websock.OPEN = 1
      // 发给后端的发送心跳
      websock.send(
        JSON.stringify({
          cmd: 7,
          msg: "ping",
          msgType: "",
          userId: userId,
        })
      );
      HeartbeatTimeoutover = setTimeout(function() {
        if (HeartbeatTimeoutnum < 5) {
          HeartbeatTimeoutnum++;
          initWebSocket();
        } else {
          closeWebsocket();
        }
      }, 120000);
    } else {
      if (errCallbacknum < 3) {
        errCallbacknum++;
        errCallbacktover = setTimeout(function() {
          initWebSocket();
        }, 120000);
        //console.log(errCallbacknum)
       
      } else {
        closeWebsocket();
      }
    
    }
  }, 30000);
}
/**
 * 发起websocket请求函数
 * @param {string} url ws连接地址
 * @param {Object} agentData 传给后台的参数
 * @param {function} successCallback 接收到ws数据，对数据进行处理的回调函数
 * @param {function} errCallback ws连接错误的回调函数
 */
export function sendWebsocket(url, agentData, successCallback, errCallback) {
  wsUrl = url;
  initWebSocket();
  //messageCallback = successCallback
  //errorCallback = errCallback;
  websocketSend(agentData);
}

/**
 * 关闭websocket函数
 */
export function closeWebsocket() {
  if (websock) {
    errCallbacknum = 0;
  HeartbeatTimeoutnum=1
  clearTimeout(HeartbeatTimeout);
  HeartbeatTimeout = null;
  clearTimeout(HeartbeatTimeoutover);
  HeartbeatTimeoutover = null;
  clearTimeout(errCallbacktover);
  errCallbacktover = null;
    websock.close(); // 关闭websocket
    websock.onclose(); // 关闭websocket
  }
}
